package logic

import (
	"context"
	"encoding/json"
	"errors"
	"user_srv/cache"
	"user_srv/models/mysql"

	"user_srv/internal/svc"
	"user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type BookReleaseLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBookReleaseLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BookReleaseLogic {
	return &BookReleaseLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BookReleaseLogic) BookRelease(in *user.BookReleaseRequest) (*user.BookReleaseResponse, error) {
	// todo: add your logic here and delete this line
	book := mysql.Book{
		UserId:     in.UserId,
		NovelTitle: in.NovelTitle,
		Writer:     in.Writer,
		BookCover:  in.BookCover,
	}
	err := book.Create()
	if err != nil {
		logx.Info("发布小说信息失败")
		return nil, errors.New("发布小说信息失败")
	}
	marshal, err := json.Marshal(&book)
	if err != nil {
		return nil, err
	}
	cache.Rdb.HMSet(l.ctx, string(marshal))

	return &user.BookReleaseResponse{
		BookId: int64(book.ID),
	}, nil
}
